package com.zhike.utils.file;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.net.URL;

import javax.servlet.http.HttpServletResponse;

public class FileUtil {

    /**
     * 计算文件大小
     * 
     * @param fileSizeBytes
     * @return
     */
    public static String convert(long fileSizeBytes) {
        double fileSizeKB = fileSizeBytes / 1024.0;

        if (fileSizeKB < 1024) {
            long size = Math.round(fileSizeKB);
            return String.format("%dKB", size <= 0 ? 1 : size);
        } else {
            double fileSizeMB = fileSizeKB / 1024.0;
            if (fileSizeMB < 1024) {
                return String.format("%dMB", Math.round(fileSizeMB));
            } else {
                double fileSizeGB = fileSizeMB / 1024.0;
                return String.format("%dGB", fileSizeGB);
            }
        }
    }

    public static String removeParams(String filename) {
        int index = filename.indexOf("?");
        return filename.substring(0, index);
    }

    public static void downloadWithUrl(String downloadUrl, HttpServletResponse res) {
        try {
            BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream());
            InputStream in = null;
            int bufferSize = 1024;
            try {
                URL url = new URL(downloadUrl);
                in = url.openStream();

                byte[] buffer = new byte[bufferSize];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
